﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 试验站服务
    /// </summary>
    [ApiDescriptionSettings(Name = "ExperimentStation", Order = 149)]
    [Route("api")]
    public class ExperimentStationService : IExperimentStationService, IDynamicApiController, ITransient
    {

        private readonly IRepository<ExperimentStation> _experimentStationRep;  // 设备仪器表仓储

        public ExperimentStationService(IRepository<ExperimentStation> experimentStationRep)
        {
            _experimentStationRep = experimentStationRep;
        }
        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("experimentStation/add")]
        public async Task Add(AddExperimentStationInput input)
        {
            var isExist = await _experimentStationRep.DetachedEntities.AnyAsync(u => u.Name == input.Name);
            if (isExist)
                throw Oops.Oh("已存在相同名称试验站");

            var experimentStation = input.Adapt<ExperimentStation>();

            await experimentStation.InsertAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost("experimentStation/delete")]
        public async Task Delete(long id)
        {
            var experimentStation = await _experimentStationRep.Include(s=>s.EquipmentInfos).Include(s=>s.Teams).FirstOrDefaultAsync(u => u.Id == id);
            if (experimentStation == null)
                throw Oops.Oh("不存在此数据");

            if (experimentStation.Teams.Count > 0)
            {
                throw Oops.Oh("此试验站已关联试验班组信息，请勿直接删除！");
            }
            if (experimentStation.EquipmentInfos.Count > 0)
            {
                throw Oops.Oh("此试验站已关联仪器设备信息，请勿直接删除！");
            }

            await experimentStation.DeleteAsync();
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        [HttpGet("experimentStation/detail")]
        public async Task<ExperimentStation> Detail(long id)
        {
            var experimentStation = await _experimentStationRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (experimentStation == null)
                throw Oops.Oh("不存在此数据！");
            return experimentStation;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [HttpPost("experimentStation/edit")]
        public async Task Edit(EditExperimentStationInput input)
        {
            var experimentStation = await _experimentStationRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (experimentStation == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _experimentStationRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同名称试验站");

            var experimentStationModel = input.Adapt<ExperimentStation>();

            await experimentStationModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("experimentStation/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _experimentStationRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = x.Name
            }).ToList();
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        [HttpGet("experimentStation/page")]
        public async Task<PageResult<ExperimentStationOutput>> QueryPage([FromQuery] ExperimentStationPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var inspector = !string.IsNullOrEmpty(input.Inspector?.Trim());
            var experimentStations = await _experimentStationRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where((inspector, u => EF.Functions.Like(u.Inspector, $"%{input.Inspector.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new ExperimentStationOutput
                                         {
                                             Id = u.Id,
                                             Name = u.Name,
                                             Inspector = u.Inspector,
                                             QualityChief = u.QualityChief,
                                             Checker = u.Checker,
                                             Remark = u.Remark,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return experimentStations;
        }
    }
}
